<template>
  <a-row style="padding-bottom: 2%">
    <div style="padding-left: 1%">
      <a-tag color="green"> {{ redisname }}</a-tag>
    </div>
    <div style="padding-left: 0.5%">
      <a-tag color="red"> Redis {{ totalCount }}</a-tag>
    </div>
    <div style="padding-left: 50%">
      <a-col>
        <a-input-search
          v-model:value="searchValue"
          placeholder="搜索"
          style="width: 200px"
          @search="onSearch"
        />
      </a-col>
    </div>

    <div style="padding-left: 3%">
      <a-col>
        <a-space>
          <a-button type="primary" @click="GeTData">
            <ReloadOutlined />
          </a-button>
        </a-space>
      </a-col>
    </div>
  </a-row>
  <div>
    <a-table :data-source="data">
      <a-table-column key="index" title="序号" data-index="index" />
      <a-table-column key="data" title="数据" data-index="data">
        <template v-slot="{ text }">
          <div style="overflow: hidden">
            <a-tooltip :title="text" color="gray">
              <a-tag
                @click="handlein(text)"
                color="green"
                :style="{
                  width: '75vw',
                }"
                :title="text"
                >{{ text }}
              </a-tag>
            </a-tooltip>
          </div>
        </template>
      </a-table-column>
    </a-table>
    <a-spin v-if="loading" size="large" />
  </div>

  <!-- 模态框 -->
  <a-modal
    v-model:open="Modalopen"
    :title="modelID"
    width="80%"
    wrap-class-name="full-modal"
    @ok="handleout"
  >
    <div class="scrollable-div">
      <json-viewer :value="jsonData" copyable boxed sort></json-viewer>
      <div style="padding-bottom: 10%">
        <div class="splide">
          <a-spin v-if="loadingModel" size="large" class="spin" />
        </div>
      </div>
    </div>
    <a-button type="primary" @click="exportData">导出JSON文件</a-button>
  </a-modal>
</template>

<script>
import { ReloadOutlined } from "@ant-design/icons-vue";
import axios from "axios";
import { message } from "ant-design-vue";
import download from "downloadjs";

export default {
  components: {
    ReloadOutlined,
  },
  data() {
    return {
      dbname: "",
      redisname: "",
      password: "",
      host: "",
      searchValue: "",
      data: [],
      loading: false,
      kafkaNum: 0,
      totalCount: 0,
      Modalopen: false,
      jsonData: "",
      loadingModel: false,
      type: "",
    };
  },
  methods: {
    exportData() {
      const jsonDataStr = JSON.stringify(this.jsonData, null, 2);
      const fileName = new Date().getTime() + ".json";
      download(jsonDataStr, fileName, "application/json");
    },
    handlein(value) {
      this.jsonData = [];
      this.loadingModel = true;
      this.Modalopen = true;
      this.isJSON(value);
      this.loadingModel = false;
    },
    isJSON(str) {
      const initText = str;
      if (typeof str == "string") {
        try {
          var obj = JSON.parse(str);
          if (typeof obj == "object" && obj) {
            this.jsonData = obj;
            return true;
          } else {
            this.jsonData = {
              文本: initText,
            };
            return false;
          }
        } catch (e) {
          try {
            str = str.replace(/\\"/g, '"');
            str = str.replace(/"{/g, "{");
            str = str.replace(/}"/g, "}");
            str = str.replace(/\\/g, "");
            const obj = JSON.parse(str);
            if (typeof obj == "object" && obj) {
              this.jsonData = obj;
              return true;
            } else {
              this.jsonData = {
                文本: initText,
              };
              return false;
            }
          } catch {
            console.log("error：" + str + "!!!" + e);
            this.jsonData = {
              文本: initText,
            };
            return false;
          }
        }
      } else {
        const initText = String(str);
        this.jsonData = {
          文本: initText,
        };
      }
    },
    handleout() {
      this.Modalopen = false;
    },
    onSearch() {
      if (this.searchValue.trim() === "") {
        // 如果搜索关键字为空，则显示全部数据
        this.GeTData();
      } else {
        // 使用筛选条件过滤数据
        const regex = new RegExp(this.searchValue, "i");
        this.data = this.data.filter((item) => {
          return regex.test(item.data);
        });
        this.addIndexToData(); // 更新索引
      }
    },

    addIndexToData() {
      this.data.forEach((item, index) => {
        item.index = index + 1;
      });
    },
    GeTData() {
      this.loading = true; // 开始加载，显示 loading 效果
      this.data = [];
      axios
        .post("/api/redis/get/data", {
          db: this.dbname,
          host: this.host,
          password: this.password,
          Name: this.redisname,
          type: this.type,
        })
        .then((response) => {
          this.data = response.data.data;
          const msg = response.data.msg;
          this.addIndexToData();
          this.loading = false; // 数据加载完成，隐藏 loading 效果
          message.info(msg);
          this.totalCount = this.data.length;
        })
        .catch((error) => {
          message.info(error.response.data.msg);
          this.loading = false; // 数据加载出错，隐藏 loading 效果
        });
    },
  },
  created() {
    this.redisname = this.$route.query.name;
    this.host = this.$route.query.host;
    this.dbname = this.$route.query.db;
    this.password = this.$route.query.password;
    this.type = this.$route.query.type;
    this.GeTData();
  },
};
</script>

<style>
.right-align {
  text-align: right;
}
</style>
